package com.qikux.dao.impl;

import com.qikux.dao.ResourceDao;
import com.qikux.dto.ResourceDTO;
import com.qikux.entity.Resource;
import com.qikux.entity.ResourceType;
import com.qikux.vo.PageVo;
import org.haredot.annotation.Repository;
import org.haredot.callback.PreparedStatementCallback;
import org.haredot.utils.DBUtils;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

@Repository
public class ResourceDaoImpl implements ResourceDao {

    @Override
    public List<ResourceType> findTypes() {
        String sql = "select * from tb_resource_type where del = 0";

        return DBUtils.queryForList(sql, ResourceType.class);
    }

    @Override
    public int saveResource(Resource resource) {

        String sql = "insert into tb_resource(resource_name, resource_url, keywords, type_id, score, description, user_id, size, ext, create_time) values(" +
                "#{resourceName}, #{resourceUrl}, #{keywords}, #{typeId}, #{score}, #{description}, #{userId}, #{size}, #{ext}, now())";
        return DBUtils.update(resource, sql);
    }

    @Override
    public List<ResourceDTO> findResourceByTypeId(Long typeId, PageVo<ResourceDTO> pageVo) {
        String sql = "select id, resource_name, size, score, ext from tb_resource where del = 0 and type_id = ? and state = 2 order by id desc limit ?, ?";
        return DBUtils.queryForList(sql, ResourceDTO.class, typeId, pageVo.getOffset(), pageVo.getRows());
    }

    @Override
    public long findResourceByTypeIdCount(Long typeId) {
        String sql = "select count(1) from tb_resource where del = 0 and type_id = ? and state = 2 ";

        return DBUtils.execute(sql, ps -> {
            ps.setLong(1, typeId);
            ResultSet resultSet = null;
            try {
                resultSet = ps.executeQuery();

                if (resultSet.next()) {
                    return resultSet.getLong(1);
                }
                return 0L;
            } finally {
                if (resultSet != null) {
                    resultSet.close();
                    resultSet = null;
                }
            }
        });
    }
}
